package uk.ac.imperial.gpaexpress.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

public class UploadWidget extends Composite {

	private static final Binder binder = GWT.create(Binder.class);

	interface Binder extends UiBinder<Widget, UploadWidget> {}
	@UiField FileUpload fileUpload;
	@UiField FormPanel uploadForm;
	@UiField Button uploadButton;
	@UiField Button cancelUploadButton;
	
	UserInterface ui;
	
	public UploadWidget(UserInterface ui) {
		initWidget(binder.createAndBindUi(this));
		uploadForm.setMethod(FormPanel.METHOD_POST);
		uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART); 
		uploadForm.setAction("/Upload");
		
		this.ui = ui;
	}
	
	@UiHandler("cancelUploadButton") 
	void onCancel(ClickEvent e){
		DialogBox parent = (DialogBox) uploadForm.getParent().getParent().getParent();
		parent.hide();
	}
	
	@UiHandler("uploadButton")
	void uploadClick(ClickEvent e) {
		ui.tickerBusy();
		uploadForm.submit();
	}
	
	@UiHandler("uploadForm")
	void onUpload(SubmitEvent e) {

	}
	
	@UiHandler("uploadForm")
	void onUploadComplete(SubmitCompleteEvent e) {
		String model_xml = e.getResults();
		if(model_xml.equals("")){
			Window.alert("Please select a valid gpepa file.");
		}
		else{
			ui.tickerIdle();

			// Get all parameter sets for this model and load the default
			try {
				Document dom = XMLParser.parse(model_xml);
				NodeList modelNodes = dom.getElementsByTagName("model");
				Element modelEm = (Element)modelNodes.item(0);
				ui.modelList.addItem(modelEm.getAttribute("title") + " #" + modelEm.getAttribute("id"));
				ui.modelList.setSelectedIndex(ui.modelList.getItemCount()-1);

				ui.populateTabs(model_xml);
				ui.populateParamList();
				
				DialogBox parent = (DialogBox) uploadForm.getParent().getParent().getParent();
				parent.hide();
				
			} catch (RequestException e1) {
				e1.printStackTrace();
			}
		}
	}
}
